package com.sgb.kjwl.view.ui.activity.manage

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.text.Html
import android.text.InputFilter
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import com.bumptech.glide.Glide
import com.luck.picture.lib.entity.LocalMedia
import com.sgb.kjwl.AppActivity
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.ActivityWebsiteEditGroupBinding
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent
import com.sgb.kjwl.di.manage.EnterpriseManageModule
import com.sgb.link.entity.PickFilterEntity
import com.sgb.kjwl.model.entity.manage.GroupDetailEntity
import com.sgb.kjwl.utils.ReplaceUtils
import com.swgk.core.event.EventConstant
import com.sgb.kjwl.view.event.self.EditMessageEvent
import com.sgb.alimaplibrary.SelectAddressActivity
import com.sgb.kjwl.view.widget.SelectAlbumPopWindow
import com.sgb.link.view.widget.TwoLevelMultipleChoiceWindow
import com.sgb.kjwl.view.widget.manage.EmojiExcludeFilter
import com.sgb.kjwl.view.widget.manage.MImgGetter
import com.sgb.kjwl.viewmodel.manage.WebSiteEditGroupModel
import com.sgb.link.view.widget.OneAndTwoLevelMultipleChoiceWindow
import com.swgk.core.base.di.AppComponent
import com.swgk.core.customview.ItemInputTextView
import com.swgk.core.dialog.DialogHelper
import com.swgk.core.util.MToast
import org.greenrobot.eventbus.EventBus
import java.io.File
import javax.inject.Inject


class WebSiteEditGroupActivity : AppActivity(), ItemInputTextView.OnWholeItemClickListener {
    @Inject
    lateinit var mViewModel : WebSiteEditGroupModel
    private lateinit var mBinding : ActivityWebsiteEditGroupBinding

    //相册选择弹窗
    private var selectAlbumPopWindow: SelectAlbumPopWindow? = null

    private var mGroupDetailEntity : GroupDetailEntity ?= null

    private var cityNames : ArrayList<String> = ArrayList()
    private var cityDTOs : ArrayList<GroupDetailEntity.Companion.CityDTOSEntity> = ArrayList()

    private var historyList  : List<PickFilterEntity<Any>> = ArrayList<PickFilterEntity<Any>>()

    lateinit var comReallyTypes: ArrayList<PickFilterEntity<*>>

    lateinit var window: OneAndTwoLevelMultipleChoiceWindow

    lateinit var manageTypeList:ArrayList<PickFilterEntity<List<PickFilterEntity<*>>>>
    //经营类型

    private var headPic = ""

    companion object{
        const val REQUEST_CODE_PIC = 255;
        const val RESULT_CODE_WEB = 100 // 返回

        const val REQUEST_CODE_WEB = 101 // 请求
        const val KEY_ENTITY = "key_entity"

        fun start (context : Context) {
            val intent = Intent(context, WebSiteEditGroupActivity::class.java)
            context.startActivity(intent)
        }

        fun start (context : Context, entity : GroupDetailEntity?) {
            val intent = Intent(context, WebSiteEditGroupActivity::class.java)
            intent.putExtra(KEY_ENTITY, entity)
            context.startActivity(intent)
        }

    }

    override fun setupActivityComponent(appComponent: AppComponent?) {
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent)
            .enterpriseManageModule(EnterpriseManageModule(this)).build().inject(this)
    }


    override fun initView() {
        if (intent != null){
            mGroupDetailEntity = intent.getSerializableExtra(KEY_ENTITY) as GroupDetailEntity
        }
        if (mGroupDetailEntity == null){
            finish()
            return
        }
        comReallyTypes = ArrayList()
        manageTypeList =ArrayList()
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_website_edit_group)
        mBinding.include.titleView.setText(R.string.self_message_describe)
        mBinding.ivUpdataImage.setOnClickListener(this)
        mBinding.ivDelect.setOnClickListener(this)
        mBinding.include.ivBack.setOnClickListener(this)
        mBinding.llAddressView.setOnClickListener(this)
        mBinding.llServiceCity.setOnClickListener(this)
        mBinding.tvIntroduction.setOnClickListener(this)
        mBinding.allconenttype.setOnClickListener(this)
        mBinding.tvSave.setOnClickListener(this)
        mBinding.tvItvGroupNumber.setInputType(EditorInfo.TYPE_CLASS_NUMBER)
        mBinding.tvItvPhone.setInputType(EditorInfo.TYPE_CLASS_NUMBER)
        mBinding.tvItvGroupNumber.setInfilterType(ItemInputTextView.TYPE_DEFAULT)
        mBinding.itemTvMajorBusiness.editText?.filters = arrayOf<InputFilter>(EmojiExcludeFilter())
//        mBinding.itemTvMajorBusiness.setEnable(false)
        mViewModel.urlString.observe(this, {//上传成功返回链接
            if (!TextUtils.isEmpty(it)){
                showAvatar(it)
            }
        })
        mViewModel.cityArea.observe(this, {
            showMarketArea(it)
        })
        mViewModel.message.observe(this, {
            if (!TextUtils.isEmpty(it)) {
                MToast.showToast(this, it)
                EventBus.getDefault().post(
                    EditMessageEvent.make(
                        EventConstant.EVENT_EDIT_MESSAGE_SUCCESS,
                        mGroupDetailEntity!!
                    )
                )
                finish()
            }
        })
        mBinding.viewModel = mGroupDetailEntity
        renderView(mGroupDetailEntity)
        //        binding.comServiceTypeDetail.setEnable(false);
        //        binding.comServiceTypeDetail.setEnable(false);
        mViewModel.businessType.observe(
            this,
            { pickFilterEntities ->
                if (pickFilterEntities != null) {
                    manageTypeList.clear()
                    manageTypeList.addAll(pickFilterEntities)
                    showManageTypePop()
                }
            })
    }

     fun renderView(entity: GroupDetailEntity?){
        if (entity == null){
            return
        }
//         if (!TextUtils.isEmpty(entity.businessType) && !TextUtils.isEmpty(entity.businessTypeNo)) {
//             val serviceTypeNames: Array<String> =
//                 entity.businessType.split(",".toRegex()).toTypedArray()
//             val serviceTypes: Array<String> =
//                 entity.businessTypeNo.split(",".toRegex()).toTypedArray()
//             if (serviceTypeNames.size == serviceTypes.size) {
//                 var entity1: PickFilterEntity<*>
//                 comReallyTypes.clear()
//                 for (i in serviceTypeNames.indices) {
//                     entity1 = PickFilterEntity<Any?>()
//                     entity1.name = serviceTypeNames[i]
//                     entity1.no = serviceTypes[i]
//                     comReallyTypes.add(entity1)
//                 }
//             }
//         }
         if (!TextUtils.isEmpty(entity!!.mainBusiness)){
             mBinding.itemTvMajorBusiness.editText.setText(entity.mainBusiness)
         }
         if (!TextUtils.isEmpty(entity!!.mainOtherBusiness)){
             mBinding.huixian.visibility=View.VISIBLE
             mBinding.huixian.setText(entity.mainOtherBusiness)
         }
//         if (!TextUtils.isEmpty(entity!!.newMainBusinessName)){
//             mBinding.huixian.visibility=View.VISIBLE
//             mBinding.huixian.setText(entity.newMainBusinessName)
//         }
         mBinding.tvItvWorkType.setText(entity.businessType)
        val des = ReplaceUtils.getHtml(entity.teamDes)
        mBinding.tvIntroduction.text = Html.fromHtml(des, MImgGetter(this, mBinding.tvIntroduction), null)
        mBinding.tvAddress.text = entity.businessAddress
        if (entity.cityDTOS != null && entity.cityDTOS!!.isNotEmpty()) {
            val sb = StringBuilder("")
            historyList = entity.cityDTOS!!.map {
                sb.append(it.areaName).append(",")
                PickFilterEntity<Any>().apply {
                    this.name = it.areaName
                    this.no = it.xzcode
                }

            }
            mBinding.tvItvServiceCity.text = sb.substring(0, sb.length - 1)
        } else if (entity.serviceCityName.isNotEmpty()) {
            mBinding.tvItvServiceCity.text = entity.serviceCityName.joinToString(",")
        }
        showAvatar(entity.logo)
    }

    /*
     * 请求市场区域返回的数据
     * */
    fun showMarketArea(list: ArrayList<PickFilterEntity<List<PickFilterEntity<*>>>>) {
        (historyList as ArrayList).clear()
        if (list.isEmpty()){
            return
        }
        val window = TwoLevelMultipleChoiceWindow(this)
        window.setTitle("市场区域")
        window.setBgView(mBinding.grayLayout)
        window.setOnResultClick { list1: List<PickFilterEntity<Any>> ->
            cityNames.clear()
            cityDTOs.clear()
            val builder = StringBuilder()
            val cityNos = StringBuilder()
            var cityDTOSEntity : GroupDetailEntity.Companion.CityDTOSEntity
            for (item in list1){
                builder.append(item.name).append(",")
                cityNos.append(item.no).append(",")
                cityDTOSEntity = GroupDetailEntity.Companion.CityDTOSEntity()
                cityDTOSEntity.areaName = item.name
                cityDTOSEntity.xzcode = item.no
                cityNames.add(item.name)
                cityDTOs.add(cityDTOSEntity)
            }
            mGroupDetailEntity!!.serviceCityName = cityNames
            mGroupDetailEntity!!.cityDTOS= cityDTOs
            mGroupDetailEntity!!.serveCity = cityNos.substring(0, cityNos.length - 1)
            mBinding.tvItvServiceCity.text = builder.substring(0, builder.length - 1)
            (historyList as ArrayList).clear()
            (historyList as ArrayList).addAll(list1)
        }
        window.setData(list, historyList)
        window.showPopwindow(mBinding.llAddressView, Gravity.BOTTOM, 0, 0)
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when(v!!.id){
            R.id.iv_delect -> {
                showAvatar("")
            }
            R.id.iv_updata_image -> {
                if (selectAlbumPopWindow == null) {
                    initAlbumPop()
                }
                showAlbumPop()
            }
            R.id.iv_back -> {
                finish()
            }
            R.id.ll_address_view -> {
                val intent = Intent()
                intent.setClass(this, SelectAddressActivity::class.java)
                intent.putExtra(SelectAddressActivity.TITLE, "所在地区")
                intent.putExtra(SelectAddressActivity.HINT, "请输入所在地区")
                intent.putExtra(SelectAddressActivity.SAVE_TEXT, "确定")
                if (TextUtils.isEmpty(mGroupDetailEntity!!.latiTude) || TextUtils.isEmpty(mGroupDetailEntity!!.longiTude)){
                    intent.putExtra(SelectAddressActivity.LATITUDE, 34.20843)
                    intent.putExtra(SelectAddressActivity.LONGTITUDE, 108.91962)
                } else {
                    intent.putExtra(SelectAddressActivity.LATITUDE, mGroupDetailEntity!!.latiTude.toDouble())
                    intent.putExtra(SelectAddressActivity.LONGTITUDE, mGroupDetailEntity!!.longiTude.toDouble())
                }
                startActivityForResult(intent, REQUEST_CODE_PIC)
            }
            R.id.tv_introduction -> {
                mViewModel.getH5Url(mGroupDetailEntity!!.teamDes, "quillEditor", REQUEST_CODE_WEB, "团队描述")
            }
            R.id.tv_save -> {
                checkMessageAndCommit()
            }
            R.id.ll_service_city -> {
                mViewModel.getMarketArea()
            }
            R.id.allconenttype ->{
                if (!manageTypeList.isEmpty()) {
                    showManageTypePop()
                } else {
                    mViewModel.getBusinessType1()
                }
            }
        }
    }
    private fun showManageTypePop() {
        if (manageTypeList.isEmpty()) return
        window = OneAndTwoLevelMultipleChoiceWindow(this@WebSiteEditGroupActivity)
        window.setTitle("经营类型")
        window.setBgView(mBinding.grayLayout)
        window.setOnResultClick(OneAndTwoLevelMultipleChoiceWindow.OnResultClick { list1: List<PickFilterEntity<*>> ->
            if (list1.size > 20) {
                MToast.showToast(this, "最多选择20个")
                return@OnResultClick
            }
            val builderName = java.lang.StringBuilder()
            val builderCode = java.lang.StringBuilder()
            for (entity in list1) {
                builderName.append(entity.name).append(",")
                builderCode.append(entity.no).append(",")
            }
            comReallyTypes.clear()
            comReallyTypes.addAll(list1)
            mBinding.tvItvWorkType.setText(builderName.substring(0, builderName.length - 1))
            mGroupDetailEntity!!.businessType =builderName.substring(0, builderName.length - 1)
            mGroupDetailEntity!!.businessTypeNo =builderCode.substring(0, builderCode.length - 1)
        })
        window.setHistory(manageTypeList, comReallyTypes)
        window.showPopwindow(mBinding.tvItvWorkType, Gravity.BOTTOM, 0, 0)
    }
    private fun checkMessageAndCommit() {
        if (TextUtils.isEmpty(mBinding.tvItvGroupName.content)){
            MToast.showToast(this, "请输入团队名称")
            return
        }
        if (TextUtils.isEmpty(mBinding.tvItvGroupNumber.content)){
            MToast.showToast(this, "请输入团队人数")
            return
        }
        if (TextUtils.isEmpty(mBinding.tvItvLeader.content)){
            MToast.showToast(this, "请输入负责人")
            return
        }
//        if (TextUtils.isEmpty(mBinding.tvItvWorkType.content)){
//            MToast.showToast(this, "请选择经营类型")
//            return
//        }
        if (TextUtils.isEmpty(mBinding.tvItvServiceCity.text)){
            MToast.showToast(this, "请选择市场区域")
            return
        }
        mGroupDetailEntity!!.serviceCityName = mBinding.tvItvServiceCity.text.split(",")
        val sb = StringBuilder("")
        mGroupDetailEntity!!.cityDTOS!!.map {
            sb.append(it.xzcode).append(",")
        }
        mGroupDetailEntity!!.serveCity =sb.substring(0, sb.length - 1)
        if (TextUtils.isEmpty(mBinding.tvAddress.text)){
            MToast.showToast(this, "请输入所在地址")
            return
        }
//        if (TextUtils.isEmpty(mBinding.itemTvMajorBusiness.editContent)){
//            MToast.showToast(this, "请输入主营业务")
//            return
//        }
        mGroupDetailEntity!!.mainBusiness =mBinding.itemTvMajorBusiness.editContent
        mGroupDetailEntity!!.logo = headPic
        mViewModel.addOrUpdateGroupMsg(mGroupDetailEntity!!)
    }


    private fun showAvatar(avatar: String) {
        if (TextUtils.isEmpty(avatar)) {
            mBinding.ivDelect.visibility = View.GONE
            mBinding.ivUpdataImage.setImageResource(R.drawable.sck)
        } else {
            mBinding.ivDelect.visibility = View.VISIBLE
            //Glide展示图片
            Glide.with(this) //加载设置宽高限制
                .load("$avatar?x-oss-process=image/resize,m_fixed,h_100") //显示圆图
                //                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                //设置为头像
                .into(mBinding.ivUpdataImage)
        }
        headPic = avatar
    }

    //展开popuwindw
    private fun showAlbumPop() {
        //判断是否在未展示的情况
        if (!selectAlbumPopWindow!!.isShowing) {
            //满足条件展示
            selectAlbumPopWindow!!.showDownPopwindow(mBinding.grayLayout, true)
        }
    }

    private fun initAlbumPop() {
        if (selectAlbumPopWindow == null) {
            //满足条件，创建SelectAlbumPopWindow
            selectAlbumPopWindow = SelectAlbumPopWindow(this)
        }
        //设置背景
        selectAlbumPopWindow!!.setBgView(mBinding.grayLayout)
        //设置点击回调
        selectAlbumPopWindow!!.setOnResultClick { key1, key2, key3 ->
            val type = key1 as Int
            if (type == 0) {
                pictureSelector(true, 500, 1)
                selectAlbumPopWindow!!.dismiss()
            }
        }
    }

    //结果回调
    override fun onPictureSelectorResult(selectList: List<LocalMedia>) {
        // 获取到图片的本地路径
        val path = selectList[0].realPath
        //保存在文件中
        if (!TextUtils.isEmpty(path)) {
            val file = File(path)
            //接口上传文件
            mViewModel.uploadAvatar(activity, file)
            //上传时，出现上传弹窗
            DialogHelper.showProgressDialog(this, null, "头像上传中...", 0, false, null)
                .setCanceledOnTouchOutside(false)
        } else {
            MToast.showToast(applicationContext, "获取图片失败！")
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_WEB && resultCode == RESULT_CODE_WEB){ //团队描述
            if (data == null) {
                return
            }
            var body = data.getStringExtra("body")?.trim()
            mGroupDetailEntity!!.teamDes = body
            body = ReplaceUtils.getHtml(body!!)
            mBinding.tvIntroduction.text = Html.fromHtml(body, MImgGetter(activity, mBinding.tvIntroduction), null)
        }
        if (resultCode != Activity.RESULT_OK) return
        when (requestCode) { //地图地址选择回调
            REQUEST_CODE_PIC -> {
                if (data == null) return
                setAddressText(data)
            }
        }
    }

    /*
     * 请求地图地址返回的数据
     * */
    private fun setAddressText(data: Intent) {
        val lat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0.0)
        val lon = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0.0)
        val address = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION)
        mGroupDetailEntity!!.latiTude = lat.toString() + ""
        mGroupDetailEntity!!.longiTude = lon.toString() + ""
        mGroupDetailEntity!!.businessAddress = address ?: ""
        mBinding.tvAddress.text = address
    }

    override fun OnWholeItemClick(view: View?) {
        when(view!!.id) {
            R.id.tv_itv_service_city -> {
            mViewModel.getMarketArea()
        }
        }
    }
}